package com.chen.tliaswebtest.service.impl;

import com.chen.tliaswebtest.exception.TliasException;
import com.chen.tliaswebtest.mapper.ClazzMapper;
import com.chen.tliaswebtest.mapper.StudentMapper;
import com.chen.tliaswebtest.pojo.Clazz;
import com.chen.tliaswebtest.pojo.PageResult;
import com.chen.tliaswebtest.service.ClazzService;
import com.chen.tliaswebtest.utils.EscapeUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/7/24
 * 班级服务实现类
 */
@Service
// spring事务默认只回滚运行时异常，编译时异常不会回滚
// 指定属性rollbackFor = {Exception.class}，可以捕获所有异常进行回滚
@Transactional(rollbackFor = {Exception.class})
public class ClazzServiceImpl implements ClazzService {
    private final ClazzMapper clazzMapper;
    private final StudentMapper studentMapper;

    public ClazzServiceImpl(ClazzMapper clazzMapper, StudentMapper studentMapper) {
        this.clazzMapper = clazzMapper;
        this.studentMapper = studentMapper;
    }

    @Override
    public PageResult listByPage(String name, LocalDate begin, LocalDate end,
                                 Integer page, Integer pageSize) {
        PageMethod.startPage(page, pageSize);
        List<Clazz> clazzList = clazzMapper.selectAllByPage(EscapeUtils.escapeLikePattern(name), begin, end, page, pageSize);
        Page<Clazz> result = (Page<Clazz>) clazzList;
        return PageResult.builder().total(result.getTotal()).rows(result.getResult()).build();
    }

    @Override
    public void removeClazzById(Integer id) {
        if (studentMapper.countByClazzId(id) > 0) {
            throw new TliasException("对不起，当前班级下有学生，不能直接删除！");
        }
        clazzMapper.deleteById(id);
    }

    @Override
    public void addClazz(Clazz clazz) {
        if (clazzMapper.selectAll().stream().map(Clazz::getName)
                .anyMatch(s -> s.equals(clazz.getName()))) {
            throw new TliasException("班级名称已存在！");
        }
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.add(clazz);
    }

    @Override
    public Clazz getClazzById(Integer id) {
        return clazzMapper.selectById(id);
    }

    @Override
    public void updateClazz(Clazz clazz) {
        clazzMapper.updateClazz(clazz);
    }

    @Override
    public List<Clazz> list() {
        return clazzMapper.selectAll();
    }
}
